import 'package:adjust_sdk/adjust.dart';
import 'package:adjust_sdk/adjust_attribution.dart';
import 'package:adjust_sdk/adjust_config.dart';
import 'package:business_plugin/business/config_business/config_business.dart';
import 'package:business_plugin/business/report_utils/report_utils.dart';
import 'package:business_plugin/business/report_utils/shared_preferences_tools/shared_preferences_tools.dart';
import 'package:business_plugin/utils/business_tools.dart';
import 'package:get/get.dart';

/// adjust归因服务
class AdjustAttributionService extends GetxService {
  static AdjustAttributionService get to => Get.find();
  //  以下都是都属于自然用户  Organic自然用户 作弊用户标识 谷歌搜索的自然用户
  static const _mOrganicFlag = ["", "Organic", "Untrusted Devices", "Google Organic Search", "No User Consent"];

  //是哪个平台来的用户
  String get adNetwork => SharedPreferencesTools.getString(ConfigBusiness.config.adNetwork, defaultValue: "");
  //广告活动名称，表示用户通过哪个广告活动(Campaign)安装或打开了您的应用
  String get campaignName => SharedPreferencesTools.getString(ConfigBusiness.config.campaignName, defaultValue: "");
  //广告组名称，表示用户通过哪个广告组(Adgroup)安装或打开了您的应用
  String get adgroup => SharedPreferencesTools.getString(ConfigBusiness.config.adgroup, defaultValue: "");
  //广告创意名称，表示用户通过哪个广告创意(Creative)安装或打开了您的应用
  String get creative => SharedPreferencesTools.getString(ConfigBusiness.config.creative, defaultValue: "");
  //是否是买量用户
  bool get isPromoteUser => _mOrganicFlag.contains(adNetwork) ? false : true;
  //获取设备id
  String get adid => SharedPreferencesTools.getString(ConfigBusiness.config.adid, defaultValue: "");

  //记录开始时间
  DateTime? startTime;
  @override
  void onInit() {
    super.onInit();
  }

  static bool isInitialized = false;

  Future<void> initializeService() async {
    if (isInitialized) return;
    await _initAdjust();
    isInitialized = true;
  }

  Future<void> _initAdjust() async {
    final environment = ConfigBusiness.config.adjustIsDebug ? AdjustEnvironment.sandbox : AdjustEnvironment.production;
    // const environment = AdjustEnvironment.production;
    final adjustConfig = AdjustConfig(ConfigBusiness.config.adjustId, environment);
    //设置了 Adjust SDK 的日志输出级别为"详细"模式。
    adjustConfig.logLevel = ConfigBusiness.config.adjustLogLevel;

    // TrackingStatus status = await BusinessTools.getAttPermission();
    // if (status != TrackingStatus.notDetermined) {}

    if (adNetwork.isEmpty) {
      _startQueryAttribution(adjustConfig);
    } else {
      ConfigBusiness.adjustCallback?.call(isPromoteUser);
    }

    // // 设置事件成功回调
    // adjustConfig.eventSuccessCallback = (AdjustEventSuccess eventSuccess) {
    //   BusinessTools.log("Adjust 事件上报成功: ${eventSuccess.eventToken}");
    //   // 可以通过事件token判断是否为特定的广告收益事件
    // };

    // // 设置事件失败回调
    // adjustConfig.eventFailureCallback = (AdjustEventFailure eventFailure) {
    //   BusinessTools.log("Adjust 事件上报失败: ${eventFailure.eventToken}, 错误: ${eventFailure.message}");
    // };

    // // 在 AdjustAttributionService 中的配置中添加
    // adjustConfig.sessionSuccessCallback = (AdjustSessionSuccess sessionSuccess) {
    //   BusinessTools.log("Adjust 会话成功: ${sessionSuccess.message}");
    //   // 广告收益会在会话包中发送
    // };

    // adjustConfig.sessionFailureCallback = (AdjustSessionFailure sessionFailure) {
    //   BusinessTools.log("Adjust 会话失败: ${sessionFailure.message}");
    // };
    Adjust.initSdk(adjustConfig);

    // 添加推送功能
    if (GetPlatform.isIOS) {
      // iOS 端的推送令牌会通过原生代码设置
      // 已在 AppDelegate.swift 中实现
      if (ConfigBusiness.deviceToken != null && ConfigBusiness.deviceToken!.isNotEmpty) {
        Adjust.setPushToken(ConfigBusiness.deviceToken!);
      }
    } else if (GetPlatform.isAndroid) {
      // Android 需要在 Flutter 中设置
      // 获取 FCM 令牌并设置
    }

    ReportUtils.logEvent("adjust_init");
    startTime = DateTime.now();
  }

  /// 获取 Adjust 设备 ID
  Future<String> getAdjustDeviceId() async {
    if (adid.isNotEmpty) {
      return adid;
    }
    try {
      // 获取 Adjust 提供的设备 ID (ADID)
      String? adid = await Adjust.getAdid();
      if (adid != null) {
        // 保存 ADID 到本地存储
        SharedPreferencesTools.setString(ConfigBusiness.config.adid, adid);
      }
      return adid ?? '';
    } catch (e) {
      BusinessTools.log('获取 Adjust 设备 ID 失败: $e');
      return '';
    }
  }

  _startQueryAttribution(AdjustConfig adjustConfig) {
    adjustConfig.attributionCallback = (AdjustAttribution? attributionChangedData) {
      ReportUtils.logEvent("adjust_Get_Success");
      if (isPromoteUser) {
        //如果已经是买量用户了就不用保存了
        return;
      }
      final campaignName = attributionChangedData?.campaign ?? "";
      SharedPreferencesTools.setString(ConfigBusiness.config.campaignName, campaignName);
      final adgroup = attributionChangedData?.adgroup ?? "";
      SharedPreferencesTools.setString(ConfigBusiness.config.adgroup, adgroup);
      final creative = attributionChangedData?.creative ?? "";
      SharedPreferencesTools.setString(ConfigBusiness.config.creative, creative);
      final adNetwork = attributionChangedData?.network ?? "";
      SharedPreferencesTools.setString(ConfigBusiness.config.adNetwork, adNetwork);

      //上报
      ReportUtils.tdAnalyticsUserSetOnce({"ad_network": adNetwork});
      ReportUtils.tdAnalyticsUserSetOnce({"campaign": campaignName});
      ReportUtils.tdAnalyticsUserSetOnce({"adgroup": adgroup});
      ReportUtils.tdAnalyticsUserSetOnce({"creative": creative});
      reportPromoteUser();

      ConfigBusiness.adjustCallback?.call(isPromoteUser);
    };
  }

  //上报买量用户
  void reportPromoteUser() async {
    if (isPromoteUser) {
      //获取当前时间，与startTime时间相差多少秒
      startTime ??= DateTime.now();
      final duration = DateTime.now().difference(startTime!);
      final seconds = (duration.inMilliseconds / 1000.0).ceil();
      ReportUtils.logEvent("adjust_Get_Promote", properties: {
        "network_name": adNetwork,
        "Pass_Time": seconds,
      });
    }
  }

  Future<String?> getIdfa() async {
    try {
      return await Adjust.getIdfa();
    } catch (e) {
      BusinessTools.log('获取IDFA失败: $e');
      return null;
    }
  }

  Future<String?> getIdfv() async {
    try {
      return await Adjust.getIdfv();
    } catch (e) {
      BusinessTools.log('获取IDFV失败: $e');
      return null;
    }
  }

  // 获取AdjustAttribution
  Future<String?> getAdNetwork() async {
    try {
      AdjustAttribution adjustAttribution = await Adjust.getAttribution();
      BusinessTools.log("adNetwork: ${adjustAttribution.network}");
      return adjustAttribution.network;
    } catch (e) {
      BusinessTools.log("获取Adjust数据失败");
      return null;
    }
  }

  @override
  void onClose() {
    super.onClose();
  }
}
